<template>
  <div class="container">
    <!-- 上半部分：统计信息 -->
    <div class="stats-container">
      <!-- 左侧统计 -->
      <div class="left-stats">
        <div class="stat-item">
          <div class="stat-label">总数量</div>
          <div class="stat-value1 total">{{ totalCount }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">在线数量</div>
          <div class="stat-value1 online">{{ onlineCount }}</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">离线数量</div>
          <div class="stat-value1 offline">{{ offlineCount }}</div>
        </div>
        <div class="grid-item">
          <!-- 手动更新按钮 -->
          <button class="refresh-btn" @click="handleRefresh">
            <i class="refresh-icon">🔄</i> 手动更新
          </button>
        </div>
      </div>
      
      <!-- 竖线分隔符 -->
      <div class="divider"></div>
      
      <!-- 右侧统计 - 动态调整方框大小 -->
      <div class="right-stats">
        <div class="grid-container" ref="gridContainer">
          <div class="grid-row">
            <div class="grid-item">
              <span class="stat-label">运行：</span>
              <div class="stat-value running" :style="statValueStyle">{{ runningCount }}</div>
            </div>
            <div class="grid-item">
              <span class="stat-label">故障：</span>
              <div class="stat-value fault" :style="statValueStyle">{{ faultCount }}</div>
            </div>
            <div class="grid-item">
              <span class="stat-label">其他</span>
              <div class="stat-value others" :style="statValueStyle">{{ othersCount }}</div>
            </div>
          </div>
          <div class="grid-row">
            <div class="grid-item">
              <span class="stat-label">待机：</span>
              <div class="stat-value standby" :style="statValueStyle">{{ standbyCount }}</div>
            </div>
            <div class="grid-item">
              <span class="stat-label">空闲：</span>
              <div class="stat-value idle" :style="statValueStyle">{{ idleCount }}</div>
            </div>
            <div class="grid-item"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 下半部分：数据表格 -->
    <div class="data-table">
      <!-- 表格内容不变 -->
      <table>
        <thead>
          <tr>
            <th v-for="column in columns" :key="column.key">
              <span>{{ column.title }}</span>
            </th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in tableData" :key="index">
            <td v-for="column in columns" :key="column.key">
              {{ item[column.key] }}
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script>
export default {
  name: 'DashboardPage',
  data() {
    return {
      // 统计数字（不变）
      totalCount: 0,
      onlineCount: 0,
      offlineCount: 0,
      runningCount: 0,
      faultCount: 0,
      standbyCount: 0,
      idleCount: 0,
      othersCount: 0,
      date_from_mes: [],
      
      // 表格配置（不变）
      columns: [  
        { key: 'name', title: '设备名称' },
        { key: 'serial_no', title: '资产编号' },
        { key: 'ccd_status', title: '设备状态' },
        { key: 'mesid', title: 'MESID' }
      ],      
      tableData: [
        { name: '设备A', serial_no: 1, ccd_status: '运行中',  mesid: '2023-08-15 10:30' },
        { name: '设备B', serial_no: 2, ccd_status: '待机', mesid: '2023-08-15 09:45' },
        { name: '设备C', serial_no: 3, ccd_status: '空闲',  mesid: '2023-08-15 11:20' },
        { name: '设备D', serial_no: 4, ccd_status: '故障',  mesid: '2023-08-15 08:15' },
        { name: '设备E', serial_no: 5, ccd_status: '运行中',  mesid: '2023-08-15 10:55' }
      ],
      
      // 动态样式计算相关
      containerWidth: 0,
      containerHeight: 0
    };
  },
  mounted() {
    this.search_db()
    // 初始化尺寸并监听窗口变化
    this.calculateContainerSize()
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    // 移除事件监听
    window.removeEventListener('resize', this.handleResize)
  },
  computed: {
    // 动态计算状态方框的样式
    statValueStyle() {
      if (!this.containerWidth || !this.containerHeight) return {}
      
      // 计算基础尺寸（根据容器大小按比例分配）
      // 一行3个元素，减去间距和标签宽度
      const baseWidth = (this.containerWidth * 0.9) / 3 // 宽度占容器90%，均分3份
      const baseHeight = (this.containerHeight * 0.4) // 高度占容器40%（两行分配）
      
      // 根据内容长度动态调整（数字越长宽度越大）
      const adjustWidthByContent = (count) => {
        const digitCount = count.toString().length
        // 基础宽度 + 数字长度补偿（每个数字增加10px）
        return Math.max(baseWidth, 80 + digitCount * 10)
      }
      
      // 返回最终样式（取所有状态中最大的宽度保证对齐）
      const maxCount = Math.max(
        this.runningCount, 
        this.faultCount, 
        this.othersCount,
        this.standbyCount,
        this.idleCount
      )
      
      return {
        width: `${adjustWidthByContent(maxCount)}px`,
        height: `${baseHeight}px`,
        fontSize: `${Math.min(baseHeight * 0.4, 24)}px` // 字体大小随高度变化
      }
    }
  },
  methods: {
    // 计算容器尺寸
    calculateContainerSize() {
      if (this.$refs.gridContainer) {
        const rect = this.$refs.gridContainer.getBoundingClientRect()
        this.containerWidth = rect.width
        this.containerHeight = rect.height
      }
    },
    // 窗口大小变化时重新计算
    handleResize() {
      // 使用防抖避免频繁计算
      clearTimeout(this.resizeTimer)
      this.resizeTimer = setTimeout(() => {
        this.calculateContainerSize()
      }, 100)
    },
    
    // 原有数据方法（不变）
    search_db(){
      this.tableData = []
      console.log("1111")
      var ccdstatus = {"run":"运行","fault":"故障","waiting":"待机","no":"未排产","other":"其他"}
      this.http.get('api/wsz_shebei/shebei_db_taizhang',
                          {}).then((reslut_) => {
                            console.log("WWWWW",reslut_)
                            var reslut = reslut_["rows"]
                            this.date_from_mes = reslut
                            this.totalCount = reslut.length
                            for(let i=0;i<reslut.length;i++){
                              if(['run', 'waiting'].includes(reslut[i]["ccd_status"])){
                                this.onlineCount += 1;
                              }else{
                                this.offlineCount += 1;
                              }

                              if(reslut[i]["ccd_status"] == "run"){
                                this.runningCount += 1
                              }
                              else if(reslut[i]["ccd_status"] == "waiting"){
                                this.standbyCount += 1
                              }
                              else if(reslut[i]["ccd_status"] == "fault"){
                                this.faultCount+=1
                              }
                              else if(reslut[i]["ccd_status"] == "no"){
                                this.idleCount += 1
                              }else{
                                this.othersCount +=1
                              }
                              
                              this.tableData.push({
                                serial_no:reslut[i]["serial_no"],
                                name:reslut[i]["name"],
                                ccd_status:ccdstatus[reslut[i]["ccd_status"]],
                                mesid:reslut[i]["mesid"],
                              })
                            }                            
                        }).catch((error) => {
                            console.log("失败",error)
                        });
    },
    search_mes_shebeiTZ(){
      this.resetStats();
      this.tableData = []
      var ccdstatus = {"run":"运行","fault":"故障","waiting":"待机","no":"未排产","other":"其他"}
      this.http.get('api/wsz_shebei/shebeitaizhang',
                          {}).then((reslut) => {
                            this.date_from_mes = reslut
                            this.totalCount = reslut.length
                            console.log(this.date_from_mes)

                            for(let i=0;i<reslut.length;i++){
                              if(['run', 'waiting'].includes(reslut[i]["ccd_status"])){
                                this.onlineCount += 1;
                              }else{
                                this.offlineCount += 1;
                              }

                              if(reslut[i]["ccd_status"] == "run"){
                                this.runningCount += 1
                              }
                              else if(reslut[i]["ccd_status"] == "waiting"){
                                this.standbyCount += 1
                              }
                              else if(reslut[i]["ccd_status"] == "fault"){
                                this.faultCount+=1
                              }
                              else if(reslut[i]["ccd_status"] == "no"){
                                this.idleCount += 1
                              }else{
                                this.othersCount +=1
                              }
                              
                              this.tableData.push({
                                serial_no:reslut[i]["serial_no"],
                                name:reslut[i]["name"],
                                ccd_status:ccdstatus[reslut[i]["ccd_status"]],
                                mesid:reslut[i]["mesid"],
                              })
                            }                            
                        }).catch((error) => {
                            console.log("失败",error)
                        });
    },
    resetStats(){
      this.totalCount = 0;
      this.onlineCount = 0;
      this.offlineCount = 0;
      this.runningCount = 0;
      this.faultCount = 0;
      this.standbyCount = 0;
      this.idleCount = 0;
      this.othersCount = 0;
    },
    handleRefresh(){
      console.log("开始刷新数据...");
      this.search_mes_shebeiTZ();
    }
  }
};
</script>

<style scoped>
/* 基础样式不变，移除stat-value的固定宽高 */
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  font-family: Arial, sans-serif;
  padding: 20px;
  box-sizing: border-box;
}

.stats-container {
  display: flex;
  height: 25%;
  margin-bottom: 25px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  padding: 15px;
}

.left-stats {
  display: flex;
  flex: 1;
  justify-content: space-around;
}

.right-stats {
  flex: 1;
  display: flex;
  padding-left: 25px;
}

/* 右侧网格布局 - 确保容器可被测量 */
.grid-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  box-sizing: border-box; /* 确保padding不影响尺寸计算 */
}

.grid-row {
  display: flex;
  flex: 1;
  justify-content: space-around;
  align-items: center; /* 垂直居中 */
}

.grid-item {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  flex: 1;
  padding: 0 15px;
  box-sizing: border-box;
  width: 30px;
}

.divider {
  width: 1px;
  background-color: #e0e0e0;
  margin: 10px 25px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 10px;
  min-width: 100px;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
  font-weight: 500;
}

.grid-item .stat-label {
  font-size: 15px;
  color: #555;
  font-weight: 500;
  margin-right: 12px;
  min-width: 50px;
  text-align: right;
}

/* 统计值样式 - 移除固定宽高，使用动态计算值 */
.stat-value1 {
  min-width: 200px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
  font-size: 22px;
  font-weight: bold;
  color: white;
  box-shadow: 0 2px 6px rgba(0,0,0,0.15);
  transition: transform 0.3s ease;
}

/* 动态尺寸的状态框 - 仅保留基础样式 */
.stat-value {
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
  font-weight: bold;
  color: white;
  box-shadow: 0 2px 6px rgba(0,0,0,0.15);
  transition: transform 0.3s ease;
  box-sizing: border-box; /* 确保尺寸计算正确 */
}

.stat-value:hover {
  transform: translateY(-3px);
}

/* 颜色样式不变 */
.total { background: linear-gradient(135deg, #4a6fa5, #3a5a8c); }
.online { background: linear-gradient(135deg, #4caf50, #388e3c); }
.offline { background: linear-gradient(135deg, #f44336, #d32f2f); }
.running { background: linear-gradient(135deg, #2196f3, #1976d2); }
.fault { background: linear-gradient(135deg, #ff9800, #f57c00); }
.standby { background: linear-gradient(135deg, #9c27b0, #7b1fa2); }
.idle { background: linear-gradient(135deg, #607d8b, #455a64); }
.others { background: linear-gradient(135deg, #730cd9, #455a64); }

/* 按钮和表格样式不变 */
.refresh-btn {
  padding: 10px 20px;
  background-color: #1976d2;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
}

.refresh-btn:hover {
  background-color: #1565c0;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

.refresh-btn:active {
  transform: translateY(0);
}

.data-table {
  flex: 1;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: auto;
  box-shadow: 0 2px 10px rgba(0,0,0,0.05);
  max-height: calc(100vh - 25% - 50px);
}

table {
  width: 100%;
  border-collapse: collapse;
  position: relative;
}
thead {
  position: sticky;
  top: 0;
  z-index: 2;
  font-size: 20px;
  background: linear-gradient(135deg, #c31a1a, #106cc8);
}
th {
  text-align: center;
  padding: 15px 20px;
  font-weight: 600;
  border-bottom: 2px solid #e0e0e0;
  color: #fff;
}

td {
  text-align: center;
  vertical-align: middle;
  padding: 12px 20px;
  border-bottom: 1px solid #eee;
}

tbody tr:hover {
  background-color: #f5f9ff;
}

tbody tr:nth-child(even) {
  background-color: #fafafa;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .stats-container {
    flex-direction: column;
    height: auto;
  }
  
  .divider {
    width: 100%;
    height: 1px;
    margin: 15px 0;
  }
  
  .left-stats {
    margin-bottom: 15px;
  }
  
  .right-stats {
    padding-left: 0;
  }
  
  .grid-container {
    width: 100%;
  }
  
  .grid-row {
    margin-bottom: 10px;
  }
  
  .grid-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .grid-item .stat-label {
    margin-bottom: 5px;
    text-align: left;
  }
  
  .refresh-btn {
    width: 100%;
    justify-content: center;
  }
}
</style>